import {
    Entity,
    PrimaryGeneratedColumn,
    Column,
    ManyToOne,
    CreateDateColumn,
    JoinColumn,
} from 'typeorm';
import { ApiProperty } from '@nestjs/swagger';
import { Conversation } from './conversation.entity';

enum MessageRole {
    USER = 'user',
    ASSISTANT = 'assistant',
    SYSTEM = 'system',
}

enum MessageType {
    TEXT = 'text',
    IMAGE = 'image',
    FILE = 'file',
    OBJECT_STRING = 'object_string',
    ANSWER = 'answer',
    FUNCTION_CALL = 'function_call',
    TOOL_OUTPUT = 'tool_output',
}

enum MessageStatus {
    PENDING = 'pending',
    COMPLETED = 'completed',
    FAILED = 'failed',
}

@Entity()
export class Message {
    @PrimaryGeneratedColumn('uuid')
    @ApiProperty({ description: '消息唯一标识' })
    id: string;

    @Column()
    @ApiProperty({ description: '所属对话ID' })
    conversationId: string;

    @Column({ nullable: true })
    @ApiProperty({ description: 'Coze消息ID' })
    cozeMessageId: string;

    @Column({ type: 'enum', enum: MessageRole })
    @ApiProperty({ enum: MessageRole, description: '消息角色' })
    role: MessageRole;

    @Column({ type: 'enum', enum: MessageType })
    @ApiProperty({ enum: MessageType, description: '消息类型' })
    type: MessageType;

    @Column({ type: 'text' })
    @ApiProperty({ description: '消息内容' })
    content: string;

    @Column({ type: 'enum', enum: MessageStatus, default: MessageStatus.PENDING })
    @ApiProperty({ enum: MessageStatus, description: '消息状态' })
    status: MessageStatus;

    @Column({ type: 'json', nullable: true })
    @ApiProperty({ description: '消息元数据' })
    metadata: Record<string, any>;

    @Column({ type: 'json', nullable: true })
    @ApiProperty({ description: '使用量统计' })
    usage: {
        promptTokens?: number;
        completionTokens?: number;
        totalTokens?: number;
    };

    @CreateDateColumn()
    @ApiProperty({ description: '创建时间' })
    createdAt: Date;

    @Column({ nullable: true })
    @ApiProperty({ description: '完成时间' })
    completedAt: Date;

    // 关系映射
    @ManyToOne(() => Conversation, conversation => conversation.messages)
    @JoinColumn({ name: 'conversationId' })
    conversation: Conversation;
}